package com.faxsun.web.filter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.broadleafcommerce.profile.core.service.CustomerUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.GenericFilterBean;

/**
 * 偽身份验证，根据session中的id信息，构造身份认证token
 * @author songdragon 2015年5月5日
 *
 */
public class PseudoAuthenticationForShopFilter extends GenericFilterBean {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpSession session=((HttpServletRequest) request)
				.getSession();
		Boolean isLoginFromInfo = (Boolean) session.getAttribute("info_first_login");
		
		if(isLoginFromInfo!=null && isLoginFromInfo){
			Long id=(Long) session.getAttribute("_blc_overrideCustomerId");
			ArrayList<GrantedAuthority> grantRoles = new ArrayList<GrantedAuthority>();
			grantRoles.add(new SimpleGrantedAuthority("ROLE_USER"));
			UserDetails ud=new CustomerUserDetails(id, "123", "", true, false, false, false, grantRoles);
			UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(ud, "",grantRoles);
			SecurityContextHolder.getContext().setAuthentication(token);
//			session.removeAttribute("shop_first_login");
		}
		chain.doFilter(request, response);
	}

}
